package org.caowei.samples.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.caowei.samples.Utils.ExcelUtils;
import org.caowei.samples.model.User;
import org.caowei.samples.sevice.UserService;
import org.caowei.samples.vo.CommonMessageResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class UserController {

	@Autowired
	private UserService UserJdbcService;

//	@Autowired
//	private LocaleResolver localeResolver;

	@ModelAttribute("user")
	public User getUserJDBC() {
		return new User();
	}

//	@RequestMapping(value = "/changeLocale")
//	public String changeLocale(HttpServletRequest request, HttpServletResponse response, String localeType) {
//		if ("en_US".equals(localeType)) {
//			localeResolver.setLocale(request, response, Locale.US);
//		} else if ("zh_CN".equals(localeType)) {
//			localeResolver.setLocale(request, response, Locale.CHINA);
//		}
//		return "redirect:/users";
//	}

	@RequestMapping("/users")
	public String users(Model model) {
		try {
			List<User> list = UserJdbcService.findAllUsers();
			model.addAttribute("userList", list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "user/userJdbcList";
	}
	
	@ResponseBody
	@RequestMapping(value = "/uploadFile")
	public CommonMessageResultVO uploadFile(@RequestParam(value = "uploadFile") MultipartFile[] uploadFile,HttpSession session,Model model){
		CommonMessageResultVO resultVO = new CommonMessageResultVO();
		MultipartFile uploadSimpleFile = uploadFile[0];
		String fileName = uploadSimpleFile.getOriginalFilename();
		
		//获取文件后缀名
		String postfix = fileName.substring(fileName.lastIndexOf("."));
		Map<String,String> messageMap = new HashMap<String,String>();
		
		try{
			//判断文件类型只能是xlsx,xls
			if(ExcelUtils.OFFICE_EXCEL_2007_POSTFIX.equals(postfix) || ExcelUtils.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)){
				UserJdbcService.saveStudnetByExcel(uploadSimpleFile.getInputStream(),postfix);
				resultVO.setSuccess(true);
			}else{
				messageMap.put("message", "文件格式不正确!");
				resultVO.setMessageMap(messageMap);
			}
		} catch (Exception e) { 
			e.printStackTrace();
			messageMap.put("message", "批量导入失败！");
			resultVO.setMessageMap(messageMap);
		}
		return resultVO;
		
	}
	
	

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String toAdd(Model model) {
		model.addAttribute("user", new User());
		return "user/addJdbc";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String add(RedirectAttributes redirectAttributes, @Validated User user, BindingResult result) {
		 if(result.hasErrors()){
		 return "user/addJdbc";
		 }
		try {
			UserJdbcService.createUser(user);
			redirectAttributes.addFlashAttribute("message", "添加成功");
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
		return "redirect:/users";
	}

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
	public String edit(RedirectAttributes redirectAttributes, User user, @PathVariable String id) {
		try {
			user.setUserId(id);
			UserJdbcService.editUser(user);
			redirectAttributes.addFlashAttribute("message", "修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
		return "redirect:/users";
	}

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String toEdit(Model model, @PathVariable String id) {
		try {
			User user = UserJdbcService.getUserById(id);
			model.addAttribute("user", user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "user/editJdbc";
	}

	@RequestMapping(value = "/delete/{id}")
	public String delete(RedirectAttributes redirectAttributes, @PathVariable String id) {
		try {
			UserJdbcService.deleteUser(id);
			redirectAttributes.addFlashAttribute("message", "删除成功");
		} catch (Exception e) {
			redirectAttributes.addFlashAttribute("message", "删除失败");
			e.printStackTrace();
		}
		return "redirect:/users";
	}
}
